import { randomStr } from '../utils/random'
import { ipcMain } from 'electron-better-ipc'
import * as fs from 'node:fs'
import { IWorkSpaceData } from './interfaces'
import { getWorkSpaceDataDirById, getWorkSpaceDataFilePathById } from './paths'
import { readJson, writeJson } from './utils'
import { readWorkSpaceHistory, saveWorkSpaceHistory, updateWorkSpaceAccessTime } from './workSpaceHistory'

// 默认工作空间数据
export const getDefaultWorkSpaceData = (id: string, path: string): IWorkSpaceData => {
    return {
        id,
        path,
        views: {
            replace: {},
            replaceDesign: {},
            design: {}
        }
    }
}

// 创建工作空间数据
export const createWorkSpace = (path: string) => {
    const id = randomStr(8)
    // 1. 添加到历史记录中
    const history = readWorkSpaceHistory()
    // 往前面添加
    history.unshift({
        id,
        path,
        lastAccessTime: Date.now()
    })
    // 写回去
    saveWorkSpaceHistory(history)
    // 2. 在应用数据目录中添加名为id的文件夹
    fs.mkdirSync(getWorkSpaceDataDirById(id), { recursive: true })
    // 3. 创建data.json文件
    writeJson(getWorkSpaceDataFilePathById(id), getDefaultWorkSpaceData(id, path))
    // 返回id
    return id
}

// 根据目录获取工作空间id
export const getWorkSpaceId = (path: string) => {
    // 检查历史数据中是否存在
    const history = readWorkSpaceHistory()
    const index = history.findIndex((item) => item.path === path)
    if (index === -1) {
        return createWorkSpace(path)
    }
    return history[index].id
}

// 读取工作空间数据
export const readWorkSpaceData = (id: string) => {
    return readJson(getWorkSpaceDataFilePathById(id)) as IWorkSpaceData
}

// 保存工作空间数据
export const saveWorkSpaceData = (params: { id: string; data: IWorkSpaceData }) => {
    const { id, data } = params
    writeJson(getWorkSpaceDataFilePathById(id), data)
}

export const openWorkSpace = (path: string) => {
    const id = getWorkSpaceId(path)
    const data = readWorkSpaceData(id)

    // 更新最后访问时间，并放在列表最前面
    updateWorkSpaceAccessTime(id)

    return data
}

ipcMain.answerRenderer('getDefaultWorkSpaceData', ({ id, path }: { id: string; path: string }) =>
    getDefaultWorkSpaceData(id, path)
)
ipcMain.answerRenderer('createWorkSpace', createWorkSpace)
ipcMain.answerRenderer('getWorkSpaceId', getWorkSpaceId)
ipcMain.answerRenderer('readWorkSpaceData', readWorkSpaceData)
ipcMain.answerRenderer('saveWorkSpaceData', saveWorkSpaceData)
ipcMain.answerRenderer('openWorkSpace', openWorkSpace)
